<?php
// +----------------------------------------------------------------------
// | 通用PHP框架 [ ThinkPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 郑州智众 [Paulxun@qq.com]
// +----------------------------------------------------------------------
// | 官方网站: https://www.zzmind.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Vip as VipModel;
use app\user\model\MoneyTake as MoneyTakeModel;
use app\user\model\Rebate as RebateModel;
use app\user\model\Level;
use util\Tree;
use think\facade\Db;

/**
 * 佣金提现控制器
 * @package app\user\admin
 */
class Moneytake extends Admin
{
    /**
     * 申请列表
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index($id = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
		
		if ($id > 0) {
			$map[] = ['id', '=', $id];
			$search_field = [];
		} else {
			$search_field = ['user_vip.member_id' => '会员ID',  'user_vip.realname' => '姓名', 'user_vip.mobile' => '手机号'];
		}
		
		// 排序条件
		$order = $this->getOrder('create_time desc');
		
        // 数据列表
        $data_list = MoneyTakeModel::getList($map, $order);
		// 提现按钮
		$btn_access = [
			'title' => '确定提现',
			'icon'  => 'fa fa-fw fa-cny',
			'class' => 'btn btn-xs btn-primary ajax-get confirm',
			'href'  => url('pay', ['id' => '__id__']),
			'data-title' => '确认已打款？'
		];
		
		// 同意按钮
		$btn_enable = [
		    'title' => '同意',
		    'icon'  => 'fa fa-check-circle-o',
		    'class' => 'btn btn-success ajax-post confirm',
		    'href'  => url('enable')
		];
		
		// 撤销同意按钮
		$btn_disable = [
		    'title' => '撤销同意',
		    'icon'  => 'fa fa-ban',
		    'class' => 'btn btn-warning ajax-post confirm',
		    'href'  => url('disable')
		];
		
		// 导出按钮
		$btnExport = [
			'title' => '导出数据',
			'icon'  => 'fa fa-fw fa-file-excel-o',
			'class' => 'btn btn-primary',
			'href'  => url('export')
		];
		
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('Vip管理') // 设置页面标题
            ->setSearch($search_field) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['uid', '会员ID'],
                ['realname', '姓名'],
                ['mobile', '手机号'],
				['group', '会员等级', 'callback', function($value){return Level::level_list($value);}],
				['money_store', '可提现', 'callback', function($value){return '￥'. $value / 100 ;}],
				['bank', '开户行'],
				['card', '卡号'],
				['money_take', '提现金额', 'callback', function($value){return '￥'. $value / 100 ;}],
                ['create_time', '申请时间', 'datetime'],
				['remark', '备注', 'popover', 5],
                ['status', '状态', 'status', '', MoneyTakeModel::status()],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('enable', $btn_enable) // 添加顶部按钮
			->addTopButton('disable', $btn_disable) // 添加顶部按钮
			->addTopButton('delete') // 添加顶部按钮
			->addTopButton('custom', $btnExport, true) // 添加导出按钮
			->addRightButton('custom', $btn_access)
            ->addRightButtons('delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
			->addFilterList('group', Level::level_list())
			->addFilter('user_money_take.status', MoneyTakeModel::status())
			->setTableName('user_money_take') // 指定数据表名
            ->fetch(); // 渲染页面
    }
	
    /**
     * 会员提现
     * @param null $id 用户id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay($id = null)
    {
        if ($id === null) $this->error('缺少参数');
    
        // 保存数据
        if ($this->request->isAjax()) {
            $take = MoneyTakeModel::where('id', '=', $id)->find();
			if ($take) {
				if($take['status'] < 1) $this->error('请先同意申请');
				if($take['status'] > 1) $this->error('该申请已提现完成');
				$vip = VipModel::where('member_id', '=', $take['uid'])->find();
				if(!$vip) $this->error('会员信息错误');
				if ($vip['money_take'] < $take['money_take']) $this->error('可提现余额少于￥'.$take['money_take']/100);
				$money_take = $vip['money_take'];
				$vip->money_take = ['dec', $take['money_take']];
				if ($vip->save()) {
					$take->status = 2;
					$take->save();
					$save_data = [
						'uid'		=> $take['uid'],
						'type'		=> 3,
						'model'		=> 3,
						'money'		=> -$take['money_take'],
						'pre'		=> 100,
						'pay'		=> -$take['money_take'],
						'from_uid'	=> $take['uid'],
						'oid'		=> $id,
						'money_take'=> $money_take - $take['money_take'],
					];
					RebateModel::create($save_data);
					$this->success('提现完成');
				} else {
					$this->error('提现失败');
				}
			} else {
				$this->error('未找到该提现申请');
			}
        }
    }   
    /**
	 * 导出提现记录
	 * @param int $map 栏目id
	 * @return mixed
	 * @throws \think\Exception
	 */
	public function export()
	{
		if(request()->isPost()){
			$data = request()->post();
			// 查询条件
			$map =[];
			if(!isset($data['status'])) $this->error('请选择申请状态');
			if($data['status'] != 99) $map[] =['status', '=', $data['status']];
			
			if(!$data['date1'] || !$data['date2']) $this->error('时间区间必选');
			$from = strtotime($data['date1']);
			$to = strtotime($data['date2']) + 3600*24 - 1;
			
			$map[] =['create_time', 'between', [$from, $to]];
			$return = [];
			// 排序条件
			$order = 'create_time desc';
			
			// 获取查询数据，数组形式
			$order_list =  MoneyTakeModel::where($map)->order($order)->select();
			
			if(!$order_list) $this->error('该条件下无可导出数据');
			$order_list =  $order_list->toArray();
			
			foreach ($order_list as $key => $value){
				$order_list[$key]['money_take'] = $value['money_take'] / 100;
				$order_list[$key]['card'] = (string)$value['card'];
				$order_list[$key]['time'] = format_time($value['create_time']);
				$order_list[$key]['status'] = MoneyTakeModel::status($value['status']);
				$vip = VipModel::info($value['uid']);
				$order_list[$key]['uid'] = empty($vip['realname']) ? '未知' : $vip['realname'];
				$order_list[$key]['admin'] = get_nickname($vip['admin']);
			}
			$order_list[] = [
				'uid' => '合计',
				'time'=> $data['date1'].'_'.$data['date2'],
				'money_take' => array_sum(array_column($order_list, 'money_take')),
			];
			$return['list'] = $order_list;
			// 设置表头信息（对应字段名,显示表头名称）
			$head[0] = [
				'id'		=> '申请序列',
				'uid' 		=> '用户',
				'money_take'=> '提现金额（元）',
				'bank'		=> '开户行',
				'card'		=> '卡号',
				'status' 	=> '状态',
				'time' 		=> '申请时间',
				'remark' 	=> '备注',
				'admin' 	=> '操作管理员',
			];
			// 向第一行插入表头
			$return['list'] = array_merge($head, $return['list']);
			
			// 表格筛选字段
			$return['field'] = [];
			foreach ($head[0] as $key => $value){
				$return['field'][] = $key;
			}
			
			$return['title'] = '提现申请'.$data['date1'].'_'.$data['date2'];
			// 返回数据（[导出文件名:title、字段信息:field、具体数据:list]）
			$this->success('导出成功', '', $return);
		}
		$js = <<<EOF
			<script type="text/javascript">
			$('input#date1').attr("autocomplete","off");
			$('input#date2').attr("autocomplete","off");
			</script>
EOF;
		// 设置表单
		return ZBuilder::make('form')
		->setPageTips('请按需求选择数据筛选', 'info')
		->setPageTitle('选择数据')
		->addDaterange('date1,date2', '日期范围', '<span class="text-danger">提交申请的日期范围</span>')
		->addFormItems([
			['radio', 'status', '状态', '',[99 => '全部'] + MoneyTakeModel::status(), 99],
		])
		->layout(['ids' => 8, 'date1' => 8, 'date2' => 8])
		->hideBtn(['submit', 'back'])
		->addBtn('<button type="button" id="get_data" class="btn btn-info">导出数据</button>')
		->js('js/excel,js/export') // 引入外部excel.js文件
		->setExtraJs($js)
		->fetch();
	}
    /**
     * 删除Vip用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($ids = [])
    {
		$ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		$delete = MoneyTakeModel::where('id', 'in', $ids)->where('status', '=', 0)->delete();
        if ($delete) {
			$this->success('撤销成功');
		} else {
			$this->error('只能撤销待同意的申请');
		}
    }

    /**
     * 启用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($ids = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用用户
     * @param array $ids 用户id
     * @author PaulXun <paulxun@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($ids = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置产品状态：删除、禁用、启用
     * @param string $type 类型：enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
		$status = 0;
		if ($type == 'enable') {
			$status = 1;
		}
        $update = MoneyTakeModel::where('id', 'in', $ids)->where('status', '<>', 2)->update(['status' => $status, 'admin' => UID]);
		if ($update) {
			$this->success('操作成功');
		} else {
			$this->error('操作失败');
		}
        // return parent::setStatus($type, ['vip_'.$type, 'user_vip', 0, UID, implode('、', $realname)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author PaulXun <paulxun@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');

        $config  = MoneyTakeModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $config . ')，新值：(' . $value . ')';
        return parent::quickEdit(['money_take', 'user_money_take', $id, UID, $details]);
    }
}
